package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkSpaceService workSpaceService;



    /**
     * 统计指定时间区间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1.当前集合用于存放从begin 到 end 范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            //日期计算，计算指定日期之后的一天所对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //将dateList进行日期格式转换，转换为String类型
        String dataListToString = StringUtils.join(dateList, ",");

        //2.创建一个集合，存放从begin到end范围内的每天对应的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询date对应的营业额，营业额是指：某个日期内，订单状态为“已完成”的所有订单的总金额
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //select sum(amount) from orders where order_time > beginTime and order_time < endTime and status = 5
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //如果turnover为null，则说明没有数据，则赋值为0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //将turnoverList进行营业额格式转换，转换为String类型
        String turnoverListToString = StringUtils.join(turnoverList, ",");

        //3.将数据封装到TurnoverReportVO中
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(dataListToString)
                .turnoverList(turnoverListToString)
                .build();

        return turnoverReportVO;
    }


    /**
     * 统计指定时间区间内的总用户量和新增用户量
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1.当前集合用于存放从begin 到 end 范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            //日期计算，计算指定日期之后的一天所对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //将dateList进行日期格式转换，转换为String类型
        String dataListToString = StringUtils.join(dateList, ",");

        //2.创建一个集合，存放从begin到end范围内的每天对应的用户量
        List<Integer> totalUserList = new ArrayList<>();
        //创建一个集合，存放从begin到end范围内的每天对应的新增用户量
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end", endTime);

            //统计总用户量
            //select count(id) from user where create_time < endTime
            Integer totalUser = userMapper.countUserByMap(map);
            totalUser = totalUser == null ? 0 : totalUser;
            totalUserList.add(totalUser);


            //统计新增用户量
            //select count(id) from user where create_time > beginTime and create_time < endTime
            map.put("begin", beginTime);
            Integer newUser = userMapper.countUserByMap(map);
            newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);
        }

        //将totalUserList newUserList 进行用户量格式转换，转换为String类型
        String totalUserListToString = StringUtils.join(totalUserList, ",");
        String newUserListToString = StringUtils.join(newUserList, ",");

        //4.将数据封装到UserReportVO中
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(dataListToString)
                .totalUserList(totalUserListToString)
                .newUserList(newUserListToString)
                .build();
        return userReportVO;
    }


    /**
     * 统计指定时间区间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //日期列表 有效订单数 有效订单列表 订单总数 订单列表 订单完成率

        //1.当前集合用于存放从begin 到 end 范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            //日期计算，计算指定日期之后的一天所对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //将dateList进行日期格式转换，转换为String类型
        String dataListToString = StringUtils.join(dateList, ",");

        //2.效订订单数 有效订单列表 订单总数 订单列表 订单完成率

        //创建一个集合，存放从begin到end范围内的每天对应的订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //创建一个集合，存放从begin到end范围内的每天对应的有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);

            //查询每天的订单总数
            //select count(id) from orders where order_time > beginTime and order_time < endTime
            Integer orderCount = orderMapper.countOrdersByMap(map);
            orderCountList.add(orderCount);

            //查询每天的有效订单数
            //select count(id) from orders where order_time > beginTime and order_time < endTime and status = 5
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countOrdersByMap(map);
            validOrderCountList.add(validOrderCount);
        }

        //3.将数据进行格式转换 转换为String类型
        String orderCountListToString = StringUtils.join(orderCountList, ",");
        String validOrderCountListToString = StringUtils.join(validOrderCountList, ",");

        //4.时间区间内的订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的有效订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        //5.将数据封装到OrderReportVO中
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(dataListToString)
                .orderCountList(orderCountListToString)
                .validOrderCountList(validOrderCountListToString)
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return orderReportVO;
    }


    /**
     * 统计指定时间区间内的销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //查询每天销量前10的菜品名称 菜品数量
        //select od.name as name,sum(od.number) as number from order_detail od left join orders o on od.order_id = o.id
        //where o.status = 5 and o.order_time > beginTime and o.order_time < endTime
        //group by name
        //order by number desc
        //limit 0,10;

        Map map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        List<GoodsSalesDTO> goodsSalesList = orderMapper.getSalesTop10ByMap(map);
        //获取名称和数量
        List<String> nameList = goodsSalesList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //将数据进行格式转换 转换为String类型
        String nameListToString = StringUtils.join(nameList, ",");
        String numberListToString = StringUtils.join(numberList, ",");

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(nameListToString)
                .numberList(numberListToString)
                .build();


        return salesTop10ReportVO;
    }



    /**
     * 导出近30天的运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据 ---查询近30填的运营数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workSpaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));

        //2.通过POI将数据写入到Excel文件中
        try {
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            //基于已有模板创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //填充数据
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //时间
            sheet.getRow(1).getCell(1).setCellValue("时间:"+beginDate+"至"+endDate);

            //概览数据
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //明细数据
            for (int i = 0; i < 30; i++){
                LocalDate date = beginDate.plusDays(i);
                //获取当天营业数据
                BusinessDataVO businessData1 = workSpaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //填充明细数据
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }

            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
